# -*- coding: utf-8 -*-
import sys
sys.path.append("../..")
from db.mysql import MysqlClient
import requests
from common.helper import Helper
from common.config import *
from itertools import product
from urllib.parse import urlencode
from pyquery import PyQuery as pq
import json
import aiohttp, asyncio


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "个人意外综合保险"
        self.jbs = json.loads( open("./{0}-jbs".format( self.name ),mode="r").read() )
    def genProductInfo(self):
        plan = {
            "days": ["1y"],
            "people_count": ["1"],
            "accident_death": ["50000", "100000", "150000", "200000", "300000", "400000", "500000"],
            "accident_fracture": ["0", "5000", "10000"],
            "accident_medical": ["0", "5000", "10000"],
            "accident_hospital": ["0", "50/天", "100/天", "200/天"],
            "accident_disable": ["0", "1"],
            "common_traffic": ["0", "1"],
            "professions": ["A0001", "A0002", "A0003", "A0004"]
        }

        for v in product(plan["days"], plan["people_count"], plan["accident_death"], plan["accident_fracture"],
                         plan["accident_medical"], plan["accident_hospital"], plan["accident_disable"],
                         plan["common_traffic"], plan["professions"]):
            data = Helper.formatProductInfo(plan, v)
            if v[6] == "1":
                data["accident_disable"] = data["accident_death"]
            else:
                data["accident_disable"] = "0"
            if v[7] == "1":
                data["common_traffic"] = str(int(2 * int(data["accident_death"])))
            else:
                data["common_traffic"] = "0"

            yield data

    # 异步爬虫
    async def requestJson(self, dt):
        params =  self.filterPayload(dt)
        payload = urlencode(  params  ).replace("+","")
        async with semaphore:
            async with aiohttp.ClientSession() as session:
                async with session.post(url=domain[self.name]["url"], headers=domain[self.name]["header"],
                                        data=payload) as resp:
                    res = await resp.text()
                    if "price" in res:
                        price = Helper.decimalParse(json.loads(res)["price"])
                        #对应职业信息
                        if params["occupationalType"] == "A0004":
                            #一级职业
                            jbs = self.jbs["A0001"]["a0004"]
                        elif params["occupationalType"] == "A0005":
                            # 二级职业
                            jbs = self.jbs["A0002"]["a0005"]
                        elif params["occupationalType"] == "A0006":
                            # 三级职业
                            jbs = self.jbs["A0003"]["a0006"]
                        else:
                            # 四级职业
                            jbs = self.jbs["A0004"]["a0007"]
                        data = {
                            "name":self.name,
                            "company":"太平洋保险",
                            "price":price

                        }
                        print( data )
                        data.update( dt )
                        data["professions"] = "'" + json.dumps( jbs,ensure_ascii=False ) + "'"
                        self.mysql.cursor.execute(Sql.format( **data ))
                        self.mysql._conn.commit()

                    else:
                        data = {

                        }

    # 过滤payload参数
    def filterPayload(self, data=None):

        selectInfo = {
            "accident_death": {
                "50000": "2271135",
                "100000": "2271136",
                "150000": "2271137",
                "200000": "2271138",
                "300000": "2271139",
                "400000": "2271140",
                "500000": "2271141"
            },
            "accident_fracture": {
                "5000": "2271644",
                "10000": "2271645"
            },
            "accident_medical": {
                "5000": "2271646",
                "10000": "2271647",
                "50000": "2271648"
            },
            "accident_hospital": {
                "50/天": "2271649",
                "100/天": "2271650",
                "200/天": "2271651"
            },
            "accident_disable": {
                "50000": "2271652",
                "100000": "2271653",
                "150000": "2271654",
                "200000": "2271655",
                "300000": "2271656",
                "400000": "2271657",
                "500000": "2271658"
            },
            "common_traffic": {
                "100000": "2271664",
                "200000": "2271665",
                "300000": "2271666",
                "400000": "2271667",
                "600000": "2271668",
                "800000": "2271669",
                "1000000": "2271670"
            }
        }
        codes = []
        for k in data:
            if k in selectInfo:
                if data[k] == "0":
                    pass
                else:
                    premiumCd = selectInfo[k][data[k]]
                    codes.append(premiumCd + ",")

        productId = ",".join(codes)

        params = {
            "random": "3083",
            "uuid": "",
            "orderId": "",
            "plaintext": "",
            "sign": "",
            "B2EUser": "",
            "productCode": "GRYWX",
            "productSerialNo": "GRYWX_planA",
            "unitPremium": "1105",
            "respNumber": "0",
            "drivingCostomType": "0",
            "discountRate": "1",
            "bxtk_url": "https: // www.cpic.com.cn / upload / Attach / mrbj",
            "checkType": "3",
            "otherSource": "10000",
            "channelNo": "10000",
            "productIds": "2271141, 2271644, 2271648, 2271649, 2271658, 2271670,",
            "productCodes": "GRYWX_SH, GRYWX_GZ, GRYWX_YL, GRYWX_JT, GRYWX_SC, GRYWX_SG,",
            "resCodes": "$sessionMap.get('resCodes')",
            "card": "GRYWX_planA",
            "insured_occupationClass": "00, 0001, 0001001",
            "insu_first_occupationName": "一般职业",
            "insu_second_occupationName": "机关团体公司",
            "insu_third_occupationName": "内勤人员(不从事危险工作)",
            "insu_first_occupation": "00",
            "insu_second_occupation": "0001",
            "insu_occupationClass": "0001001",
            "occupationalType": "A0004",
            "GRYWX_GZ": "",
            "GRYWX_YL": "",
            "GRYWX_JT": "",
            "GRYWX_SC": "",
            "GRYWX_SG": "",
            "inceptionDate": "2020 - 05 - 05",
            "plannedEndDate": "2021 - 05 - 04",
            "commonuuid": "not find uuid",
        }
        #  一级职业
        if data["professions"] == "A0001":
            params["productIds"] = productId
        # 二级职业
        elif data["professions"] == "A0002":
            params["productIds"] = productId
            params["occupationalType"] = "A0005"
            params["insu_first_occupationName"] = "一般职业"
            params["insu_second_occupationName"] = "机关团体公司"
            params["insu_third_occupationName"] = "外勤人员(不属于本表下列职业分类所列者)"

        # 三级职业
        elif data["professions"] == "A0003":
            params["productIds"] = productId
            params["occupationalType"] = "A0006"
            params["insu_first_occupationName"] = "农畜牧业"
            params["insu_second_occupationName"] = "畜牧业"
            params["insu_third_occupationName"] = "畜牧工作人员"
        # 四级职业
        else:
            params["productIds"] = productId
            params["occupationalType"] = "A0007"
            params["insu_first_occupationName"] = "木材森林业"
            params["insu_second_occupationName"] = "森林砍伐业"
            params["insu_third_occupationName"] = "监工"

        return params

    # 获取职业信息
    def getProfessionInfo(self):
        jbs_url = "https://www.cpic.com.cn/mall/sale/shortterm/estimate?productCode=GRYWX&productSerialNo=GRYWX_planA"
        doc = pq(jbs_url)
        items = doc(".common_select option").items()

        A0004 = {
            "a0004": []
        }
        A0005 = {
            "a0005": []
        }
        A0006 = {
            "a0006": []
        }
        A0007 = {
            "a0007": []
        }
        try:
            for item in items:
                if "codedetailid" not in str(item):
                    continue
                else:
                    if item.text() == "/":
                        pass
                    else:
                        data = {
                            "occ_id": item.attr("codedetailid"),
                            "name": item.text()
                        }
                        g = lambda: requests.post(
                            url="https://www.cpic.com.cn/mall/sale/code/findPropertySubOccupation",
                            headers=domain[self.name]["header"], data="occupation=" + data["occ_id"] + "",
                            verify=True).json()
                        for x in g():

                            base = {
                                "base_id": x["codeDetailId"],
                                "name": x["label"]
                            }
                            payload = urlencode({"occupation": base["base_id"]})

                            gr = lambda: requests.post(
                                url="https://www.cpic.com.cn/mall/sale/code/findPropertySubOccupation",
                                headers=domain[self.name]["header"], data=payload, verify=True).json()
                            for y in gr():
                                if y["description"] == "A0004":
                                    A0004["a0004"].append(y["name"])
                                elif y["description"] == "A0005":
                                    A0005["a0005"].append(y["name"])
                                elif y["description"] == "A0006":
                                    A0006["a0006"].append(y["name"])
                                elif y["description"] == "A0007":
                                    A0007["a0007"].append(y["name"])
                                else:
                                    pass
        except Exception as e:
            pass

        return (A0004, A0005, A0006, A0007)

    # 执行
    def asyncTask(self):
        global semaphore,Sql
        Sql = 'INSERT INTO `accident`(`name`,`company`,`price`,`days`,`people_count`,`accident_death`,`accident_fracture`,`accident_medical`,`accident_hospital`,`accident_disable`,`common_traffic`,`professions`)VALUES("{name}","{company}","{price}","{days}","{people_count}","{accident_death}","{accident_fracture}","{accident_medical}","{accident_hospital}","{accident_disable}","{common_traffic}",{professions})'
        semaphore = asyncio.Semaphore(5)
        tasks = [self.requestJson(data) for data in self.genProductInfo()]
        event_loop = asyncio.get_event_loop()
        event_loop.run_until_complete(asyncio.gather(*tasks))
        event_loop.close()